package org.dromara.admin.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.dromara.admin.domain.vo.EmployeeVo;
import org.dromara.admin.enums.GeneralEnum;
import org.dromara.admin.service.ICompanyService;
import org.dromara.admin.service.IEmployeeService;
import org.dromara.admin.service.ISystemConfigService;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.dromara.admin.domain.bo.CompanyBo;
import org.dromara.admin.domain.vo.CompanyVo;
import org.dromara.admin.domain.Company;
import org.dromara.admin.mapper.CompanyMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 主体信息Service业务层处理
 *
 * @author Lion Li
 * @date 2025-10-10
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class CompanyServiceImpl implements ICompanyService {

    private final CompanyMapper baseMapper;
    private final IEmployeeService employeeService;
    private final ISystemConfigService systemConfigService;

    /**
     * 查询主体信息
     *
     * @param id 主键
     * @return 主体信息
     */
    @Override
    public CompanyVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询主体信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 主体信息分页列表
     */
    @Override
    public TableDataInfo<CompanyVo> queryPageList(CompanyBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Company> lqw = buildQueryWrapper(bo);
        Page<CompanyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的主体信息列表
     *
     * @param bo 查询条件
     * @return 主体信息列表
     */
    @Override
    public List<CompanyVo> queryList(CompanyBo bo) {
        LambdaQueryWrapper<Company> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Company> buildQueryWrapper(CompanyBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Company> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(Company::getId);
        lqw.like(StringUtils.isNotBlank(bo.getCompanyCode()), Company::getCompanyCode, bo.getCompanyCode());
        lqw.eq(bo.getSubjectType() != null, Company::getSubjectType, bo.getSubjectType());
        lqw.like(StringUtils.isNotBlank(bo.getShortName()), Company::getShortName, bo.getShortName());
        lqw.and(StrUtil.isNotBlank(bo.getName()),
            w -> w.like(Company::getName, bo.getName()).or().like(Company::getNamePy, bo.getName().toUpperCase()));
        lqw.like(StringUtils.isNotBlank(bo.getSignature()), Company::getSignature, bo.getSignature());
        lqw.like(StringUtils.isNotBlank(bo.getContactPerson1()), Company::getContactPerson1, bo.getContactPerson1());
        lqw.eq(StringUtils.isNotBlank(bo.getContact1()), Company::getContact1, bo.getContact1());
        lqw.like(StringUtils.isNotBlank(bo.getContactPerson2()), Company::getContactPerson2, bo.getContactPerson2());
        lqw.eq(StringUtils.isNotBlank(bo.getContact2()), Company::getContact2, bo.getContact2());
        lqw.like(StringUtils.isNotBlank(bo.getProvince()), Company::getProvince, bo.getProvince());
        lqw.like(StringUtils.isNotBlank(bo.getCity()), Company::getCity, bo.getCity());
        lqw.like(StringUtils.isNotBlank(bo.getDistrict()), Company::getDistrict, bo.getDistrict());
        lqw.like(StringUtils.isNotBlank(bo.getDetailAddress()), Company::getDetailAddress, bo.getDetailAddress());
        lqw.eq(bo.getMemberMode() != null, Company::getMemberMode, bo.getMemberMode());
        lqw.eq(bo.getMemberStatus() != null, Company::getMemberStatus, bo.getMemberStatus());
        lqw.eq(bo.getMemberExpireTime() != null, Company::getMemberExpireTime, bo.getMemberExpireTime());
        lqw.eq(bo.getSubjectStatus() != null, Company::getSubjectStatus, bo.getSubjectStatus());
        return lqw;
    }

    /**
     * 新增主体信息
     *
     * @param bo 主体信息
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(CompanyBo bo) {
        if (hasCompanyId(bo.getUserId())) {
            throw new ServiceException("用户已绑定主体!");
        }
        Company add = MapstructUtils.convert(bo, Company.class);
        validEntityBeforeSave(add);
        // 设置主体公司四位唯一随机数编码
        add.setCompanyCode(this.generateUniqueCompanyCode());
        add.setNamePy(PinyinUtil.getFirstLetter(add.getName(), "").toUpperCase());
        add.setSubjectStatus(GeneralEnum.Y);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            // 插入成功后，员工账号关联主体id
            employeeService.updateByCompanyId(bo.getUserId(), add.getId());
            // 插入成功后，添加主体公司的系统配置
            systemConfigService.insertByCompanyId(add.getId());
        }
        return flag;
    }

    /**
     * 生成唯一的四位公司编号（如：1234）
     */
    private String generateUniqueCompanyCode() {
        String code;
        boolean exists;
        do {
            // 生成四位随机数
            code = RandomUtil.randomNumbers(4);
            // 检查数据库是否已存在
            exists = this.baseMapper.exists(
                new LambdaQueryWrapper<Company>()
                    .eq(Company::getCompanyCode, code)
            );
        } while (exists);
        return code;
    }

    /**
     * 修改主体信息
     *
     * @param bo 主体信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(CompanyBo bo) {
        Company update = MapstructUtils.convert(bo, Company.class);
        if (StrUtil.isNotBlank(update.getName())) {
            update.setNamePy(PinyinUtil.getFirstLetter(update.getName(), "").toUpperCase());
        }
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Company entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除主体信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 判断用户是否绑定主体
     *
     * @param userId 用户id
     * @return 是否注册主体
     */
    @Override
    public Boolean hasCompanyId(Long userId) {
        EmployeeVo employeeVo = employeeService.queryById(userId);
        // 判断用户信息里是否存在companyId，如果存在则返回true
        boolean result = employeeVo != null && employeeVo.getCompanyId() != null;
        if (!result) {
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }
}
